package com.kyzh.core.download.down

import android.content.Context
import android.content.Intent
import android.os.Build
import android.util.Log
import com.blankj.utilcode.util.ServiceUtils.stopService
import com.gushenge.core.base.Base
import com.gushenge.core.beans.DownTaskBean
import com.gushenge.core.dao.MMKVConsts
import com.jeremyliao.liveeventbus.LiveEventBus
import com.kyzh.core.MyApplication
import com.kyzh.core.utils.FileUtils
import com.kyzh.core.utils.NetworkUtil
import com.liulishuo.okdownload.DownloadListener
import com.liulishuo.okdownload.DownloadTask
import com.liulishuo.okdownload.StatusUtil
import com.liulishuo.okdownload.UnifiedListenerManager
import org.litepal.LitePal
import java.io.File


/**
 *
 * @Author:         yu
 * @CreateDate:     2021/3/16 17:34
 */
object DownTask {
    /**
     * 存放所有任务  key作为下载地址
     */
    var map: HashMap<String, DownloadTask> = HashMap()
    lateinit var download: DownloadTask
    var mapDown :HashMap<String, DownTaskBean> =HashMap()
    /**
     * 下载的文件在SpConsts.downloadDir/游戏名字.apk
     */
    fun createDownloadTask( game: DownTaskBean) :DownloadTask{
        return DownloadTask.Builder(game.url, File(MMKVConsts.downloadDir)) //设置下载地址和下载目录，这两个是必须的参数
            .setFilename(game.name+".apk") //设置下载文件名，没提供的话先看 response header ，再看 url path(即启用下面那项配置)
            .setFilenameFromResponse(false) //是否使用 response header or url path 作为文件名，此时会忽略指定的文件名，默认false
            .setPassIfAlreadyCompleted(false) //如果文件已经下载完成，再次下载时，是否忽略下载，默认为true(忽略)，设为false会从头下载
            .setConnectionCount(1) //需要用几个线程来下载文件，默认根据文件大小确定；如果文件已经 split block，则设置后无效
            .setPreAllocateLength(false) //在获取资源长度后，设置是否需要为文件预分配长度，默认false
            .setMinIntervalMillisCallbackProcess(2000) //通知调用者的频率，避免anr，默认3000
            .setWifiRequired(false) //是否只允许wifi下载，默认为false
            .setAutoCallbackToUIThread(true) //是否在主线程通知调用者，默认为true

            //.setHeaderMapFields(new HashMap<String, List<String>>())//设置请求头
            //.addHeader(String key, String value)//追加请求头
            .setPriority(0) //设置优先级，默认值是0，值越大下载优先级越高
            .setReadBufferSize(4096) //设置读取缓存区大小，默认4096
            .setFlushBufferSize(16384) //设置写入缓存区大小，默认16384
            .setSyncBufferSize(65536) //写入到文件的缓冲区大小，默认65536
            .setSyncBufferIntervalMillis(2000) //写入文件的最小时间间隔，默认2000
            .apply {
                addHeader("Referer", Base.BASEURL)//追加请求头
            }
            .build()


    }

    /**
     * 返回1 下载完成
     */
    fun checkStatus( game: DownTaskBean):Int{
        val task = map[game.url]
        return when(task?.let { StatusUtil.getStatus(it) }){
            StatusUtil.Status.COMPLETED ->{
                1
            }
            StatusUtil.Status.RUNNING ->{
                2
            }
            StatusUtil.Status.PENDING ->{
                2
            }
            else -> 0
        }

    }

    /**
     * 返回1 下载完成
     */
    fun checkStatus( game: String):Int{
        val task = map[game]
        return when(task?.let { StatusUtil.getStatus(it) }){
            StatusUtil.Status.COMPLETED ->{
                1
            }
            StatusUtil.Status.RUNNING ->{
                2
            }
            StatusUtil.Status.PENDING ->{
                2
            }
            else -> 0
        }

    }

    /**
    下载任务
     * */
    fun downLoad( game: DownTaskBean){
        kotlin.runCatching {
            val game1 = LitePal.where("url = ?",game.url).findFirst(DownTaskBean::class.java)
            if(game1.isSaved){
                if(game1.name != game.name){
                    remove(game1)
                }
            }
        }
        NetworkUtil().checkNetworkState(MyApplication.instance)
//        if(Build.BOARD=="HUAWEI"||"HONOR"==Build.BOARD||Build.BOARD=="Huawei"||"MHA"==Build.BOARD ) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //启动前台服务
            val service = Intent(MyApplication.instance, DownService::class.java)
            service.putExtra("url",game.url)
            service.putExtra("game",game)
            service.putExtra("name",game.name)
            MyApplication.instance.startForegroundService(service)
        }else
        {
            val service = Intent(MyApplication.instance, DownService::class.java)
            service.putExtra("game",game)
            service.putExtra("url",game.url)
            service.putExtra("name",game.name)
            MyApplication.instance.startService(service)
        }
//        }

    }
    fun delect(game: DownTaskBean){
        Log.e("TAG", "postValue: ", )
        game.state =4
        val task = getTask(game)
        task?.tag = "cancel"
        task?.cancel()


    }




    fun stopService1(){
        val service = Intent(MyApplication.instance, DownService::class.java)
        stopService(service);
    }
    fun postValue(game: DownTaskBean){
        Log.e("TAG", "postValue: ", )
        mapDown[game.url]=game
        LiveEventBus.get<Map<String,DownTaskBean>>("GAMETASK").post(mapDown)
    }
    fun downEnqueue(task:DownloadTask,game: DownTaskBean){

        game.state = 1
        val unifiedListenerManager = UnifiedListenerManager()
        unifiedListenerManager.attachAndEnqueueIfNotRun(task,
            createDownloadListener(MyApplication.instance,game)
        )
        postValue(game)
        val game1 = LitePal.where("url = ?",game.url).find(
            DownTaskBean::class.java)
        if( game1!=null &&game1.size>0){
            game.updateAll("url = ?", game.url)
        }else{
            game.save()
        }
    }
    /**
     * 根据指定url  获取数据库中的game
     */
    fun getGamebyUrl(url : String):DownTaskBean?{

        kotlin.runCatching {
            val game1 = LitePal.where("url = ?",url).findFirst(DownTaskBean::class.java)
            return  game1
        }.onFailure {
            return  null
        }
        return null
    }
    /**
     * 删除任务、文件、数据库
     */
    fun remove(game: DownTaskBean){
        kotlin.runCatching {
            map[game.url]?.tag="cancel"
            map[game.url]?.cancel()
            map.remove(game.url)
                FileUtils.deleteFileExceptFolder(MMKVConsts.downloadDir+"/"+game.name+".apk")

        }

    }

    /**
     * 获取任务
     */
    fun getTask(game: DownTaskBean)= map[game.url]

    /**
     * 获取任务
     */
    fun getTaskByUrl(url: String)= map[url]

    private fun createDownloadListener(context: Context,  game:
    DownTaskBean): DownloadListener {
        return DownLoadListener(context,game)
    }
}

